/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace Oceanside
{
    class PrintRaw
    {
        // Structure and API declarions:
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public class DOCINFOA
        {
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDocName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pOutputFile;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDataType;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        private struct NetResource
        {
            [MarshalAs(UnmanagedType.U4)]
            public uint iScope;
            [MarshalAs(UnmanagedType.U4)]
            public uint iType;
            [MarshalAs(UnmanagedType.U4)]
            public uint iDisplayType;
            [MarshalAs(UnmanagedType.U4)]
            public uint iUsage;
            [MarshalAs(UnmanagedType.LPStr)]
            public string sLocalName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string sRemoteName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string sComment;
            [MarshalAs(UnmanagedType.LPStr)]
            public string sProvider;
        }
        private const uint RESOURCETYPE_DISK = 0x1;


        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern int StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

        [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndDocPrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2A(ref NetResource pstNetRes, string psPassword, string psUsername, int piFlags);
        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2A(string psName, int piFlags, int pfForce);

        public static void LoginToShare(string serverName, string user, string password)
        {
            int flags = 0;
            try
            {
                NetResource nr = new NetResource();
                nr.iScope = 2;
                nr.iType = RESOURCETYPE_DISK;
                nr.iDisplayType = 3;
                nr.iUsage = 1;
                nr.sRemoteName = serverName;
                nr.sLocalName = null;

                int rc = WNetAddConnection2A(ref nr, password, user, flags);
                if (rc != 0)
                {
                    throw new Win32Exception(rc);
                }
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PRINTSPOOL_LOGIN_TO_SHARE, ex);

                ///If we get this exception it usually occurs in development when the username or
                ///password of the print server changes and we try to access it again from the
                ///new password.  If we cancel the connection and login again, it normally clears.
                try
                {
                    ///Try to cancel and go again.
                    WNetCancelConnection2A(serverName, flags, 1);
                    NetResource nr = new NetResource();
                    nr.iScope = 2;
                    nr.iType = RESOURCETYPE_DISK;
                    nr.iDisplayType = 3;
                    nr.iUsage = 1;
                    nr.sRemoteName = serverName;
                    nr.sLocalName = null;

                    WNetAddConnection2A(ref nr, password, user, flags);
                }
                catch (Exception) { }
            }
        }

        // SendBytesToPrinter()
        // When the function is given a printer name and an unmanaged array
        // of bytes, the function sends those bytes to the print queue.
        // Returns true on success, false on failure.
        private static Int32 SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount, string docName)
        {
            Int32 docId = 0;
            try
            {
                Int32 dwError = 0, dwWritten = 0;
                IntPtr hPrinter = new IntPtr(0);
                DOCINFOA di = new DOCINFOA();
                bool bSuccess = false; // Assume failure unless you specifically succeed.

                di.pDocName = docName;
                di.pOutputFile = null;
                di.pDataType = "RAW";

                // Open the printer.
                if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
                {
                    docId = StartDocPrinter(hPrinter, 1, di);
                    // Start a document.
                    if (docId != 0)
                    {
                        // Start a page.
                        if (StartPagePrinter(hPrinter))
                        {
                            // Write your bytes.
                            bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                            EndPagePrinter(hPrinter);
                        }
                        EndDocPrinter(hPrinter);
                    }
                    ClosePrinter(hPrinter);
                }
                // If you did not succeed, GetLastError may give more information
                // about why not.
                if (bSuccess == false)
                {
                    dwError = Marshal.GetLastWin32Error();
                    Marshal.FreeCoTaskMem(pBytes);
                    throw new Win32Exception(dwError);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                Marshal.FreeCoTaskMem(pBytes);
            }
            return docId;
        }

        public static Int32 SendStringToPrinter(string szPrinterName, string szString, string docName)
        {
            IntPtr pBytes;
            Int32 dwCount;
            // How many characters are in the string?
            dwCount = szString.Length;
            // Assume that the printer is expecting ANSI text, and then convert
            // the string to ANSI text.
            pBytes = Marshal.StringToCoTaskMemAnsi(szString);
            // Send the converted ANSI string to the printer.
            return SendBytesToPrinter(szPrinterName, pBytes, dwCount, docName);
        }
    }
}

